package com.c.opt.tool;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Opt;
import com.c.opt.query.ComOptQueryWrapper;
import ntd.util.frame.auth.ToolLogin;
import ntd.util.frame.data.bo.MetaTableField;
import ntd.util.frame.javacv.tool.ToolAiUserSites;

import java.util.List;

public class ToolQuery {

    /**
     * 逻辑删除字段逻辑匹配
     * @param comOptQueryWrapper
     * @param metaTableFields
     */
    public static void initDelFlag(ComOptQueryWrapper comOptQueryWrapper, List<MetaTableField> metaTableFields) {
        MetaTableField fieldFlag = CollectionUtil.findOne(metaTableFields, metaTableField ->
                "flag".equals(metaTableField.getName()));
        Opt.ofNullable(fieldFlag).ifPresent(metaTableField -> comOptQueryWrapper.logicDelFlag());
    }

    /**
     * 默认排序字段匹配
     * @param comOptQueryWrapper
     * @param metaTableFields
     */
    public static void initOrder(ComOptQueryWrapper comOptQueryWrapper, List<MetaTableField> metaTableFields) {
        // 排序规则
        MetaTableField fieldCreatedDate = CollectionUtil.findOne(metaTableFields, metaTableField ->
                "created_date".equals(metaTableField.getName()));
        Opt.ofNullable(fieldCreatedDate).ifPresent(metaTableField -> comOptQueryWrapper.desc("created_date"));
    }

    /**
     * 数据级别权限匹配
     * @param comOptQueryWrapper
     * @param metaTableFields
     */
    public static void initDataLevel(ComOptQueryWrapper comOptQueryWrapper, List<MetaTableField> metaTableFields) {
        switch (comOptQueryWrapper.dataLevel()) {
            case DATA_LEVEL_ONLY_MY: {
                MetaTableField fieldCreatedDate = CollectionUtil.findOne(metaTableFields, metaTableField ->
                    "created_by".equals(metaTableField.getName()));
                Opt.ofNullable(fieldCreatedDate).ifPresent(metaTableField -> comOptQueryWrapper.eq("created_by", ToolLogin.getCurrUserId()));
                break;
            }
            case DATA_LEVEL_ONLY_TENANT: {
                MetaTableField fieldCreatedDate = CollectionUtil.findOne(metaTableFields, metaTableField ->
                    "tenant_id".equals(metaTableField.getName()));
                Opt.ofNullable(fieldCreatedDate).ifPresent(metaTableField -> comOptQueryWrapper.eq("tenant_id", ToolLogin.getCurrTenantId()));
                break;
            }
        }
    }

}
